package com.example.webdemo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.ScheduledFuture;

@Slf4j
public class TestTask implements Runnable{
    private RestTemplate restTemplate;

    private volatile ScheduledFuture<?> scheduledFuture;

    public TestTask(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Override
    public void run() {
        try {
            ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:8082", String.class);
            String s = entity.toString();
            log.info("get data:{}",s);
        } catch (Exception e) {
//            log.error("e:{}",e);
            log.error("error");
            return;
        }

        /**
         * 有可能任务执行太快，future还没被赋值
         */
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
        }

    }

    public void setScheduledFuture(ScheduledFuture<?> scheduledFuture) {
        this.scheduledFuture = scheduledFuture;
    }
}
